﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel;
using System.Text.RegularExpressions;

namespace LTM_Extra
{
   public  class Validator
    {

        public static class Rules
        {
            public const string CanotBeEmpty = @"^.+";
            public const string MustBeInteger = @"\d?";
            public const string MustBeEmail = @"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$";

        }

        public static class Message
        {
            public const string CanotBeEmpty = @"This field can't be empty!";
            public const string MustBeInteger = @"This filed must be integer!";
            public const string MustBeEmail = @"It's not a valide email format!";

        }

        public static void ValidateEmail(Control control)
        {
            Validate(control, Rules.MustBeEmail, Message.MustBeEmail);
        }

        public static void ValidateInteger(Control control)
        {
            Validate(control, Rules.MustBeInteger, Message.MustBeInteger);
        }


        public static void ValidateEmpty(Control control)
        {
            Validate(control, Rules.CanotBeEmpty, Message.CanotBeEmpty);
        }


        public static void Validate(Control control, string validationRule, string message)
        {
            ErrorProvider errorProvider = new ErrorProvider();

            CancelEventHandler validatingHandler = new CancelEventHandler((Object obj, CancelEventArgs arg) =>
            {
                if (!Regex.IsMatch(control.Text, validationRule))
                {
                    errorProvider.SetError(control, message);
                    errorProvider.ContainerControl = GetControlsContainer(control);
                    arg.Cancel = true;
                }
                else
                {
                    errorProvider.Clear();
                    arg.Cancel = false;
                }
            });
            Validate(control, validatingHandler);
        }

        private static ContainerControl GetControlsContainer(Control control)
        {
            Control parent=control.Parent;
            while (parent != null)
            {
                if(parent is Form)
                {
                    break;
                }
                parent = parent.Parent;
            }
            return parent as ContainerControl;
        }


        public static void Validate(Control control, CancelEventHandler validatingHandler)
        {
            control.Validating += new CancelEventHandler(validatingHandler);

        }
    }
}
